import*as e from"../../../../models/text_utils/text_utils.js";import*as t from"../../../../core/i18n/i18n.js";import*as r from"../../legacy.js";import*as n from"../../../../core/common/common.js";import*as i from"../../../../core/platform/platform.js";import*as s from"../../../../models/formatter/formatter.js";import*as o from"../../../../third_party/codemirror.next/codemirror.next.js";import*as a from"../../../components/code_highlighter/code_highlighter.js";import*as l from"../../../components/text_editor/text_editor.js";import*as c from"../../../../core/host/host.js";import*as h from"../../../../models/workspace/workspace.js";import*as d from"../../../../core/sdk/sdk.js";import*as u from"../object_ui/object_ui.js";const m=["application/javascript","application/json","application/manifest+json","text/css","text/html","text/javascript","text/x-scss"];var p={cssContent:".searchable-view{flex:1}.toolbar{background-color:var(--color-background-elevation-2);border-top:1px solid var(--color-details-hairline)}"};const g={source:"Source",prettyPrint:"Pretty print",loading:"Loading…",dSelectionRegions:"{PH1} selection regions",bytecodePositionXs:"Bytecode position `0x`{PH1}",lineSColumnS:"Line {PH1}, Column {PH2}",dCharactersSelected:"{PH1} characters selected",dLinesDCharactersSelected:"{PH1} lines, {PH2} characters selected"},w=t.i18n.registerUIStrings("ui/legacy/components/source_frame/SourceFrame.ts",g),f=t.i18n.getLocalizedString.bind(void 0,w);class x extends(n.ObjectWrapper.eventMixin(r.View.SimpleView)){options;lazyContent;prettyInternal;rawContent;formattedMap;prettyToggle;shouldAutoPrettyPrint;progressToolbarItem;textEditorInternal;baseDoc;prettyBaseDoc=null;displayedSelection=null;searchConfig;delayedFindSearchMatches;currentSearchResultIndex;searchResults;searchRegex;loadError;muteChangeEventsForSetContent;sourcePosition;searchableView;editable;positionToReveal;lineToScrollTo;selectionToSet;loadedInternal;contentRequested;wasmDisassemblyInternal;contentSet;constructor(e,t={}){super(f(g.source)),this.options=t,this.lazyContent=e,this.prettyInternal=!1,this.rawContent=null,this.formattedMap=null,this.prettyToggle=new r.Toolbar.ToolbarToggle(f(g.prettyPrint),"brackets"),this.prettyToggle.addEventListener(r.Toolbar.ToolbarButton.Events.Click,(()=>{this.setPretty(!this.prettyToggle.toggled())})),this.shouldAutoPrettyPrint=!1,this.prettyToggle.setVisible(!1),this.progressToolbarItem=new r.Toolbar.ToolbarItem(document.createElement("div")),this.textEditorInternal=new l.TextEditor.TextEditor(this.placeholderEditorState("")),this.textEditorInternal.style.flexGrow="1",this.element.appendChild(this.textEditorInternal),this.element.addEventListener("keydown",(e=>{e.defaultPrevented&&e.stopPropagation()})),this.baseDoc=this.textEditorInternal.state.doc,this.searchConfig=null,this.delayedFindSearchMatches=null,this.currentSearchResultIndex=-1,this.searchResults=[],this.searchRegex=null,this.loadError=!1,this.muteChangeEventsForSetContent=!1,this.sourcePosition=new r.Toolbar.ToolbarText,this.searchableView=null,this.editable=!1,this.positionToReveal=null,this.lineToScrollTo=null,this.selectionToSet=null,this.loadedInternal=!1,this.contentRequested=!1,this.wasmDisassemblyInternal=null,this.contentSet=!1,n.Settings.Settings.instance().moduleSetting("textEditorIndent").addChangeListener(this.#e,this)}disposeView(){n.Settings.Settings.instance().moduleSetting("textEditorIndent").removeChangeListener(this.#e,this)}async#e(){this.prettyInternal&&(await this.setPretty(!1),await this.setPretty(!0))}placeholderEditorState(e){return o.EditorState.create({doc:e,extensions:[o.EditorState.readOnly.of(!0),!1!==this.options.lineNumbers?o.lineNumbers():[],l.Config.theme()]})}editorConfiguration(e){return[o.EditorView.updateListener.of((e=>this.dispatchEventToListeners("EditorUpdate",e))),l.Config.baseConfiguration(e),l.Config.closeBrackets,l.Config.autocompletion.instance(),l.Config.showWhitespace.instance(),l.Config.allowScrollPastEof.instance(),o.Prec.lowest(l.Config.codeFolding.instance()),l.Config.autoDetectIndent.instance(),V,o.EditorView.domEventHandlers({focus:()=>this.onFocus(),blur:()=>this.onBlur(),scroll:()=>this.dispatchEventToListeners("EditorScroll"),contextmenu:e=>this.onContextMenu(e)}),o.lineNumbers({domEventHandlers:{contextmenu:(e,t,r)=>this.onLineGutterContextMenu(t.from,r)}}),o.EditorView.updateListener.of((e=>{(e.selectionSet||e.docChanged)&&this.updateSourcePosition(),e.docChanged&&this.onTextChanged()})),C,o.Prec.lowest(R),y.language.of([]),this.wasmDisassemblyInternal?(t=this.wasmDisassemblyInternal,N.init((e=>{const r=[];for(const n of t.nonBreakableLineNumbers())n<e.doc.lines&&r.push(P.range(e.doc.line(n+1).from));return o.RangeSet.of(r)}))):N,this.options.lineWrapping?o.EditorView.lineWrapping:[],!1!==this.options.lineNumbers?o.lineNumbers():[]];var t}onBlur(){}onFocus(){this.resetCurrentSearchResultIndex()}get wasmDisassembly(){return this.wasmDisassemblyInternal}editorLocationToUILocation(e,t){return this.wasmDisassemblyInternal?(t=this.wasmDisassemblyInternal.lineNumberToBytecodeOffset(e),e=0):this.prettyInternal&&([e,t]=this.prettyToRawLocation(e,t)),{lineNumber:e,columnNumber:t}}uiLocationToEditorLocation(e,t=0){return this.wasmDisassemblyInternal?(e=this.wasmDisassemblyInternal.bytecodeOffsetToLineNumber(t),t=0):this.prettyInternal&&([e,t]=this.rawToPrettyLocation(e,t)),{lineNumber:e,columnNumber:t}}setCanPrettyPrint(e,t){this.shouldAutoPrettyPrint=e&&Boolean(t),this.prettyToggle.setVisible(e)}setEditable(e){this.editable=e,this.loaded&&e!==!this.textEditor.state.readOnly&&this.textEditor.dispatch({effects:y.editable.reconfigure(o.EditorState.readOnly.of(!e))})}async setPretty(e){this.prettyInternal=e,this.prettyToggle.setEnabled(!1);const t=this.loaded,{textEditor:r}=this,n=r.state.selection.main,i=r.toLineColumn(n.from),a=r.toLineColumn(n.to);let l;if(this.prettyInternal){const e=this.rawContent instanceof o.Text?this.rawContent.sliceString(0):this.rawContent||"",t=await s.ScriptFormatter.formatScriptContent(this.contentType,e);this.formattedMap=t.formattedMapping,await this.setContent(t.formattedContent),this.prettyBaseDoc=r.state.doc;const n=this.rawToPrettyLocation(i.lineNumber,i.columnNumber),c=this.rawToPrettyLocation(a.lineNumber,a.columnNumber);l=r.createSelection({lineNumber:n[0],columnNumber:n[1]},{lineNumber:c[0],columnNumber:c[1]})}else{await this.setContent(this.rawContent||""),this.baseDoc=r.state.doc;const e=this.prettyToRawLocation(i.lineNumber,i.columnNumber),t=this.prettyToRawLocation(a.lineNumber,a.columnNumber);l=r.createSelection({lineNumber:e[0],columnNumber:e[1]},{lineNumber:t[0],columnNumber:t[1]})}t&&r.revealPosition(l,!1),this.prettyToggle.setEnabled(!0),this.updatePrettyPrintState()}getLineNumberFormatter(){if(!1===this.options.lineNumbers)return[];let e=null;if(this.wasmDisassemblyInternal){const t=this.wasmDisassemblyInternal,r=t.lineNumberToBytecodeOffset(t.lineNumbers-1).toString(16).length+1;e=e=>`0x${t.lineNumberToBytecodeOffset(Math.min(t.lineNumbers,e)-1).toString(16).padStart(r,"0")}`}else this.prettyInternal&&(e=e=>{const t=this.prettyToRawLocation(e-1,0)[0]+1;return 1===e||t!==this.prettyToRawLocation(e-2,0)[0]+1?String(t):"-"});return e?o.lineNumbers({formatNumber:e}):[]}updateLineNumberFormatter(){this.textEditor.dispatch({effects:y.lineNumbers.reconfigure(this.getLineNumberFormatter())})}updatePrettyPrintState(){this.prettyToggle.setToggled(this.prettyInternal),this.textEditorInternal.classList.toggle("pretty-printed",this.prettyInternal),this.updateLineNumberFormatter()}prettyToRawLocation(e,t=0){return this.formattedMap?this.formattedMap.formattedToOriginal(e,t):[e,t]}rawToPrettyLocation(e,t){return this.formattedMap?this.formattedMap.originalToFormatted(e,t):[e,t]}hasLoadError(){return this.loadError}wasShown(){this.ensureContentLoaded(),this.wasShownOrLoaded()}willHide(){super.willHide(),this.clearPositionToReveal()}async toolbarItems(){return[this.prettyToggle,this.sourcePosition,this.progressToolbarItem]}get loaded(){return this.loadedInternal}get textEditor(){return this.textEditorInternal}get pretty(){return this.prettyInternal}get contentType(){return this.loadError?"":this.getContentType()}getContentType(){return""}async ensureContentLoaded(){this.contentRequested||(this.contentRequested=!0,await this.setDeferredContent(this.lazyContent()),this.contentSet=!0)}async setDeferredContent(t){const i=new r.ProgressIndicator.ProgressIndicator;i.setTitle(f(g.loading)),i.setTotalWork(100),this.progressToolbarItem.element.appendChild(i.element),i.setWorked(1);const s=await t;let a,l;if(null===s.content)a=s.error,this.rawContent=s.error;else if(l=s.content,s.isEncoded){const e=new DataView(n.Base64.decode(s.content)),t=new TextDecoder;this.rawContent=t.decode(e,{stream:!0})}else if("wasmDisassemblyInfo"in s&&s.wasmDisassemblyInfo){const{wasmDisassemblyInfo:e}=s;this.rawContent=o.Text.of(e.lines),this.wasmDisassemblyInternal=e}else this.rawContent=l,this.wasmDisassemblyInternal=null;if(l&&"application/wasm"===this.contentType&&!this.wasmDisassemblyInternal){const e=n.Worker.WorkerWrapper.fromURL(new URL("../../../../entrypoints/wasmparser_worker/wasmparser_worker-entrypoint.js",import.meta.url)),t=new Promise(((t,r)=>{e.onmessage=({data:e})=>{if("event"in e){if("progress"===e.event)i?.setWorked(e.params.percentage)}else if("method"in e&&"disassemble"===e.method)"error"in e?r(e.error):"result"in e&&t(e.result)},e.onerror=r}));e.postMessage({method:"disassemble",params:{content:l}});try{const{lines:r,offsets:i,functionBodyOffsets:s}=await t;this.rawContent=l=o.Text.of(r),this.wasmDisassemblyInternal=new n.WasmDisassembly.WasmDisassembly(r,i,s)}catch(e){this.rawContent=l=a=e.message}finally{e.terminate()}}i.setWorked(100),i.done(),this.formattedMap=null,this.prettyToggle.setEnabled(!0),a?(this.loadError=!0,this.textEditor.state=this.placeholderEditorState(a),this.prettyToggle.setEnabled(!1)):this.shouldAutoPrettyPrint&&e.TextUtils.isMinified(l||"")?await this.setPretty(!0):await this.setContent(this.rawContent||"")}revealPosition(e,t){this.lineToScrollTo=null,this.selectionToSet=null;let r=0,n=0;if("number"==typeof e){const{doc:t}=this.textEditor.state;if(e>t.length)r=t.lines-1;else if(e>=0){const i=t.lineAt(e);r=i.number-1,n=e-i.from}}else r=e.lineNumber,n=e.columnNumber??0;this.positionToReveal={line:r,column:n,shouldHighlight:t},this.innerRevealPositionIfNeeded()}innerRevealPositionIfNeeded(){if(!this.positionToReveal)return;if(!this.loaded||!this.isShowing())return;const e=this.uiLocationToEditorLocation(this.positionToReveal.line,this.positionToReveal.column),{textEditor:t}=this;t.revealPosition(t.createSelection(e),this.positionToReveal.shouldHighlight),this.positionToReveal=null}clearPositionToReveal(){this.positionToReveal=null}scrollToLine(e){this.clearPositionToReveal(),this.lineToScrollTo=e,this.innerScrollToLineIfNeeded()}innerScrollToLineIfNeeded(){if(null!==this.lineToScrollTo&&this.loaded&&this.isShowing()){const{textEditor:e}=this,t=e.toOffset({lineNumber:this.lineToScrollTo,columnNumber:0});e.dispatch({effects:o.EditorView.scrollIntoView(t,{y:"start",yMargin:0})}),this.lineToScrollTo=null}}setSelection(e){this.selectionToSet=e,this.innerSetSelectionIfNeeded()}innerSetSelectionIfNeeded(){const e=this.selectionToSet;if(e&&this.loaded&&this.isShowing()){const{textEditor:t}=this;t.dispatch({selection:t.createSelection({lineNumber:e.startLine,columnNumber:e.startColumn},{lineNumber:e.endLine,columnNumber:e.endColumn})}),this.selectionToSet=null}}wasShownOrLoaded(){this.innerRevealPositionIfNeeded(),this.innerSetSelectionIfNeeded(),this.innerScrollToLineIfNeeded()}onTextChanged(){const e=this.pretty;this.prettyInternal=Boolean(this.prettyBaseDoc&&this.textEditor.state.doc.eq(this.prettyBaseDoc)),this.prettyInternal!==e&&this.updatePrettyPrintState(),this.prettyToggle.setEnabled(this.isClean()),this.searchConfig&&this.searchableView&&this.performSearch(this.searchConfig,!1,!1)}isClean(){return this.textEditor.state.doc.eq(this.baseDoc)||null!==this.prettyBaseDoc&&this.textEditor.state.doc.eq(this.prettyBaseDoc)}contentCommitted(){this.baseDoc=this.textEditorInternal.state.doc,this.prettyBaseDoc=null,this.rawContent=this.textEditor.state.doc.toString(),this.formattedMap=null,this.prettyInternal&&(this.prettyInternal=!1,this.updatePrettyPrintState()),this.prettyToggle.setEnabled(!0)}async getLanguageSupport(e){let{contentType:t}=this;"text/x.vue"===t&&((e="string"==typeof e?e:e.sliceString(0)).trimStart().startsWith("<")||(t="text/javascript"));const r=await a.CodeHighlighter.languageFromMIME(t);return r?[r,o.javascript.javascriptLanguage.data.of({autocomplete:o.completeAnyWord})]:[]}async updateLanguageMode(e){const t=await this.getLanguageSupport(e);this.textEditor.dispatch({effects:y.language.reconfigure(t)})}async setContent(e){this.muteChangeEventsForSetContent=!0;const{textEditor:t}=this,r=this.loadedInternal,n=t.editor.scrollDOM.scrollTop;this.loadedInternal=!0;const i=await this.getLanguageSupport(e),s=o.EditorState.create({doc:e,extensions:[this.editorConfiguration(e),i,y.lineNumbers.of(this.getLineNumberFormatter()),y.editable.of(this.editable?[]:o.EditorState.readOnly.of(!0))]});this.baseDoc=s.doc,t.state=s,r&&(t.editor.scrollDOM.scrollTop=n),this.wasShownOrLoaded(),this.delayedFindSearchMatches&&(this.delayedFindSearchMatches(),this.delayedFindSearchMatches=null),this.muteChangeEventsForSetContent=!1}setSearchableView(e){this.searchableView=e}doFindSearchMatches(e,t,r){this.currentSearchResultIndex=-1,this.searchRegex=e.toSearchRegex(!0),this.searchResults=this.collectRegexMatches(this.searchRegex),this.searchableView&&this.searchableView.updateSearchMatchesCount(this.searchResults.length);const n=this.textEditor;this.searchResults.length?t&&r?this.jumpToPreviousSearchResult():t?this.jumpToNextSearchResult():n.dispatch({effects:v.of(new T(this.searchRegex,null))}):n.state.field(C)&&n.dispatch({effects:v.of(null)})}performSearch(e,t,r){this.searchableView&&this.searchableView.updateSearchMatchesCount(0),this.resetSearch(),this.searchConfig=e,this.loaded?this.doFindSearchMatches(e,t,Boolean(r)):this.delayedFindSearchMatches=this.doFindSearchMatches.bind(this,e,t,Boolean(r)),this.ensureContentLoaded()}resetCurrentSearchResultIndex(){if(!this.searchResults.length)return;this.currentSearchResultIndex=-1,this.searchableView&&this.searchableView.updateCurrentMatchIndex(this.currentSearchResultIndex);const e=this.textEditor,t=e.state.field(C);t&&t.currentRange&&e.dispatch({effects:v.of(new T(t.regexp,null))})}resetSearch(){this.searchConfig=null,this.delayedFindSearchMatches=null,this.currentSearchResultIndex=-1,this.searchResults=[],this.searchRegex=null}onSearchCanceled(){const e=-1!==this.currentSearchResultIndex?this.searchResults[this.currentSearchResultIndex]:null;if(this.resetSearch(),!this.loaded)return;this.textEditor.dispatch({effects:v.of(null),selection:e?{anchor:e.from,head:e.to}:void 0,scrollIntoView:!0,userEvent:"select.search.cancel"})}jumpToLastSearchResult(){this.jumpToSearchResult(this.searchResults.length-1)}searchResultIndexForCurrentSelection(){return i.ArrayUtilities.lowerBound(this.searchResults,this.textEditor.state.selection.main,((e,t)=>e.to-t.to))}jumpToNextSearchResult(){const e=this.searchResultIndexForCurrentSelection(),t=-1===this.currentSearchResultIndex?e:e+1;this.jumpToSearchResult(t)}jumpToPreviousSearchResult(){const e=this.searchResultIndexForCurrentSelection();this.jumpToSearchResult(e-1)}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}jumpToSearchResult(e){if(!this.loaded||!this.searchResults.length||!this.searchRegex)return;this.currentSearchResultIndex=(e+this.searchResults.length)%this.searchResults.length,this.searchableView&&this.searchableView.updateCurrentMatchIndex(this.currentSearchResultIndex);const t=this.textEditor,r=this.searchResults[this.currentSearchResultIndex];t.dispatch({effects:v.of(new T(this.searchRegex,r)),selection:{anchor:r.from,head:r.to},scrollIntoView:!0,userEvent:"select.search"})}replaceSelectionWith(e,t){const r=this.searchResults[this.currentSearchResultIndex];if(!r)return;const n=this.searchRegex?.fromQuery?r.insertPlaceholders(t):t,i=this.textEditor,s=i.state.changes({from:r.from,to:r.to,insert:n});i.dispatch({changes:s,selection:{anchor:s.mapPos(i.state.selection.main.to,1)},userEvent:"input.replace"})}replaceAllWith(e,t){this.resetCurrentSearchResultIndex();const r=e.toSearchRegex(!0),n=this.collectRegexMatches(r);if(!n.length)return;const i=r.fromQuery,s=n.map((e=>({from:e.from,to:e.to,insert:i?e.insertPlaceholders(t):t})));this.textEditor.dispatch({changes:s,scrollIntoView:!0,userEvent:"input.replace.all"})}collectRegexMatches({regex:e}){const t=[];let r=0;for(const n of this.textEditor.state.doc.iterLines()){for(e.lastIndex=0;;){const i=e.exec(n);if(!i)break;if(i[0].length){const e=r+i.index;t.push(new S(e,e+i[0].length,i))}else e.lastIndex=i.index+1}r+=n.length+1}return t}canEditSource(){return this.editable}updateSourcePosition(){const{textEditor:e}=this,{state:t}=e,{selection:r}=t;if(this.displayedSelection?.eq(r))return;if(this.displayedSelection=r,r.ranges.length>1)return void this.sourcePosition.setText(f(g.dSelectionRegions,{PH1:r.ranges.length}));const{main:n}=t.selection;if(n.empty){const{lineNumber:t,columnNumber:r}=e.toLineColumn(n.head),i=this.prettyToRawLocation(t,r);if(this.wasmDisassemblyInternal){const e=this.wasmDisassemblyInternal,t=e.lineNumberToBytecodeOffset(e.lineNumbers-1).toString(16).length,r=e.lineNumberToBytecodeOffset(i[0]);this.sourcePosition.setText(f(g.bytecodePositionXs,{PH1:r.toString(16).padStart(t,"0")}))}else this.sourcePosition.setText(f(g.lineSColumnS,{PH1:i[0]+1,PH2:i[1]+1}))}else{const e=t.doc.lineAt(n.from),r=t.doc.lineAt(n.to);e.number===r.number?this.sourcePosition.setText(f(g.dCharactersSelected,{PH1:n.to-n.from})):this.sourcePosition.setText(f(g.dLinesDCharactersSelected,{PH1:r.number-e.number+1,PH2:n.to-n.from}))}}onContextMenu(e){e.consume(!0);const t=new r.ContextMenu.ContextMenu(e),{state:n}=this.textEditor,i=n.selection.main.from,s=n.doc.lineAt(i);return this.populateTextAreaContextMenu(t,s.number-1,i-s.from),t.appendApplicableItems(this),t.show(),!0}populateTextAreaContextMenu(e,t,r){}onLineGutterContextMenu(e,t){t.consume(!0);const n=new r.ContextMenu.ContextMenu(t),i=this.textEditor.state.doc.lineAt(e).number-1;return this.populateLineGutterContextMenu(n,i),n.appendApplicableItems(this),n.show(),!0}populateLineGutterContextMenu(e,t){}focus(){this.textEditor.focus()}}class S{from;to;match;constructor(e,t,r){this.from=e,this.to=t,this.match=r}insertPlaceholders(e){return e.replace(/\$(\$|&|\d+|<[^>]+>)/g,((e,t)=>"$"===t?"$":"&"===t?this.match[0]:"<"===t[0]?this.match.groups&&this.match.groups[t.slice(1,t.length-1)]||"":this.match[Number.parseInt(t,10)]||""))}}var b;!function(e){e.PERFORMANCE="performance",e.MEMORY="memory",e.COVERAGE="coverage"}(b||(b={}));const y={editable:new o.Compartment,language:new o.Compartment,lineNumbers:new o.Compartment};class T{regexp;currentRange;constructor(e,t){this.regexp=e,this.currentRange=t}map(e){return e.empty||!this.currentRange?this:new T(this.regexp,{from:e.mapPos(this.currentRange.from),to:e.mapPos(this.currentRange.to)})}static eq(e,t){return Boolean(e===t||e&&t&&e.currentRange?.from===t.currentRange?.from&&e.currentRange?.to===t.currentRange?.to&&e.regexp.regex.source===t.regexp.regex.source&&e.regexp.regex.flags===t.regexp.regex.flags)}}const v=o.StateEffect.define({map:(e,t)=>e&&e.map(t)}),C=o.StateField.define({create:()=>null,update:(e,t)=>t.effects.reduce(((e,t)=>t.is(v)?t.value:e),e&&e.map(t.changes))}),E=o.Decoration.mark({class:"cm-searchMatch"}),I=o.Decoration.mark({class:"cm-searchMatch cm-searchMatch-selected"}),R=o.ViewPlugin.fromClass(class{decorations;constructor(e){this.decorations=this.computeDecorations(e)}update(e){const t=e.state.field(C);(!T.eq(t,e.startState.field(C))||t&&(e.viewportChanged||e.docChanged))&&(this.decorations=this.computeDecorations(e.view))}computeDecorations(e){const t=e.state.field(C);if(!t)return o.Decoration.none;const r=new o.RangeSetBuilder,{doc:n}=e.state;for(const{from:i,to:s}of e.visibleRanges){let e=i;for(const o of n.iterRange(i,s)){if("\n"!==o)for(t.regexp.regex.lastIndex=0;;){const n=t.regexp.regex.exec(o);if(!n)break;if(n[0].length){const i=e+n.index,s=i+n[0].length,o=t.currentRange&&t.currentRange.from===i&&t.currentRange.to===s;r.add(i,s,o?I:E)}else t.regexp.regex.lastIndex=n.index+1}e+=o.length}}return r.finish()}},{decorations:e=>e.decorations}),P=new class extends o.GutterMarker{elementClass="cm-nonBreakableLine"},L=o.StateEffect.define(),N=o.StateField.define({create:()=>o.RangeSet.empty,update:(e,t)=>t.effects.reduce(((e,t)=>t.is(L)?e.update({add:t.value.map((e=>P.range(e)))}):e),e.map(t.changes)),provide:e=>o.lineNumberMarkers.from(e)});const V=o.EditorView.theme({"&.cm-editor":{height:"100%"},".cm-scroller":{overflow:"auto"},".cm-lineNumbers .cm-gutterElement.cm-nonBreakableLine":{color:"var(--color-non-breakable-line) !important"},".cm-searchMatch":{border:"1px solid var(--color-search-match-border)",borderRadius:"3px",margin:"0 -1px","&.cm-searchMatch-selected":{borderRadius:"1px",backgroundColor:"var(--color-selected-search-match-background)",borderColor:"var(--color-selected-search-match-background)","&, & *":{color:"var(--color-selected-search-match) !important"}}},":host-context(.pretty-printed) & .cm-lineNumbers .cm-gutterElement":{color:"var(--color-primary-old)"}});var F=Object.freeze({__proto__:null,SourceFrameImpl:x,get DecoratorType(){return b},addNonBreakableLines:L,isBreakableLine:function(e,t){const r=e.field(N);if(!r.size)return!0;let n=!1;return r.between(t.from,t.from,(()=>{n=!0})),!n}});const M={find:"Find"},O=t.i18n.registerUIStrings("ui/legacy/components/source_frame/ResourceSourceFrame.ts",M),U=t.i18n.getLocalizedString.bind(void 0,O);class D extends x{givenContentType;resourceInternal;constructor(e,t,r){super((()=>e.requestContent()),r),this.givenContentType=t,this.resourceInternal=e}static createSearchableView(e,t,r){return new j(e,t,r)}getContentType(){return this.givenContentType}get resource(){return this.resourceInternal}populateTextAreaContextMenu(e,t,r){super.populateTextAreaContextMenu(e,t,r),e.appendApplicableItems(this.resourceInternal)}}class j extends r.Widget.VBox{sourceFrame;constructor(e,t,n){super(!0),this.registerRequiredCSS(p);const i=new D(e,t);this.sourceFrame=i;const s=m.includes(t);i.setCanPrettyPrint(s,n);const o=new r.SearchableView.SearchableView(i,i);o.element.classList.add("searchable-view"),o.setPlaceholder(U(M.find)),i.show(o.element),i.setSearchableView(o),o.show(this.contentElement);const a=new r.Toolbar.Toolbar("toolbar",this.contentElement);i.toolbarItems().then((e=>{e.map((e=>a.appendToolbarItem(e)))}))}async revealPosition(e,t){this.sourceFrame.revealPosition({lineNumber:e,columnNumber:t},!0)}}var H=Object.freeze({__proto__:null,ResourceSourceFrame:D,SearchableContainer:j});class k{base64content;contentUrl;resourceType;arrayPromise;hexPromise;utf8Promise;constructor(e,t,r){this.base64content=e,this.contentUrl=t,this.resourceType=r,this.arrayPromise=null,this.hexPromise=null,this.utf8Promise=null}async fetchContentAsArray(){return this.arrayPromise||(this.arrayPromise=new Promise((async e=>{const t=await fetch("data:;base64,"+this.base64content);e(new Uint8Array(await t.arrayBuffer()))}))),await this.arrayPromise}async hex(){if(!this.hexPromise){const e=await this.fetchContentAsArray();return{content:k.uint8ArrayToHexString(e),isEncoded:!1}}return this.hexPromise}async base64(){return{content:this.base64content,isEncoded:!0}}async utf8(){return this.utf8Promise||(this.utf8Promise=new Promise((async e=>{const t=await this.fetchContentAsArray();e({content:new TextDecoder("utf8").decode(t),isEncoded:!1})}))),this.utf8Promise}createBase64View(){return new D(e.StaticContentProvider.StaticContentProvider.fromString(this.contentUrl,this.resourceType,this.base64content),this.resourceType.canonicalMimeType(),{lineNumbers:!1,lineWrapping:!0})}createHexView(){const t=new e.StaticContentProvider.StaticContentProvider(this.contentUrl,this.resourceType,(async()=>{const e=await this.fetchContentAsArray();return{content:k.uint8ArrayToHexViewer(e),isEncoded:!1}}));return new D(t,this.resourceType.canonicalMimeType(),{lineNumbers:!1,lineWrapping:!1})}createUtf8View(){const t=this.utf8.bind(this),r=new e.StaticContentProvider.StaticContentProvider(this.contentUrl,this.resourceType,t);return new D(r,this.resourceType.canonicalMimeType(),{lineNumbers:!0,lineWrapping:!0})}static uint8ArrayToHexString(e){let t="";for(let r=0;r<e.length;r++)t+=k.numberToHex(e[r],2);return t}static numberToHex(e,t){let r=e.toString(16);for(;r.length<t;)r="0"+r;return r}static uint8ArrayToHexViewer(e){let t="",r=0;for(;16*r<e.length;){const n=e.slice(16*r,16*(r+1));t+=k.numberToHex(r,8)+":";let i=0;for(let e=0;e<n.length;e++)e%2==0&&(t+=" ",i++),t+=k.numberToHex(n[e],2),i+=2;for(;i<42;)t+=" ",i++;for(let e=0;e<n.length;e++){const r=n[e];t+=r>=32&&r<=126?String.fromCharCode(r):"."}t+="\n",r++}return t}}var A=Object.freeze({__proto__:null,BinaryResourceViewFactory:k}),_={cssContent:".font-view{font-size:60px;white-space:pre-wrap;word-wrap:break-word;text-align:center;padding:15px}"};const z={font:"Font",previewOfFontFromS:"Preview of font from {PH1}"},B=t.i18n.registerUIStrings("ui/legacy/components/source_frame/FontView.ts",z),W=t.i18n.getLocalizedString.bind(void 0,B);class q extends r.View.SimpleView{url;mimeType;contentProvider;mimeTypeLabel;fontPreviewElement;dummyElement;fontStyleElement;inResize;constructor(e,t){super(W(z.font)),this.registerRequiredCSS(_),this.element.classList.add("font-view"),this.url=t.contentURL(),r.ARIAUtils.setLabel(this.element,W(z.previewOfFontFromS,{PH1:this.url})),this.mimeType=e,this.contentProvider=t,this.mimeTypeLabel=new r.Toolbar.ToolbarText(e)}async toolbarItems(){return[this.mimeTypeLabel]}onFontContentLoaded(t,r){const{content:n}=r,s=n?e.ContentProvider.contentAsDataURL(n,this.mimeType,!0):this.url;this.fontStyleElement&&(this.fontStyleElement.textContent=i.StringUtilities.sprintf('@font-face { font-family: "%s"; src: url(%s); }',t,s),this.updateFontPreviewSize())}createContentIfNeeded(){if(this.fontPreviewElement)return;const e="WebInspectorFontPreview"+ ++J;this.fontStyleElement=document.createElement("style"),this.contentProvider.requestContent().then((t=>{this.onFontContentLoaded(e,t)})),this.element.appendChild(this.fontStyleElement);const t=document.createElement("div");for(let e=0;e<X.length;++e)e>0&&t.createChild("br"),r.UIUtils.createTextChild(t,X[e]);this.fontPreviewElement=t.cloneNode(!0),this.fontPreviewElement&&(r.ARIAUtils.markAsHidden(this.fontPreviewElement),this.fontPreviewElement.style.overflow="hidden",this.fontPreviewElement.style.setProperty("font-family",e),this.fontPreviewElement.style.setProperty("visibility","hidden"),this.dummyElement=t,this.dummyElement.style.visibility="hidden",this.dummyElement.style.zIndex="-1",this.dummyElement.style.display="inline",this.dummyElement.style.position="absolute",this.dummyElement.style.setProperty("font-family",e),this.dummyElement.style.setProperty("font-size",G+"px"),this.element.appendChild(this.fontPreviewElement))}wasShown(){this.createContentIfNeeded(),this.updateFontPreviewSize()}onResize(){if(!this.inResize){this.inResize=!0;try{this.updateFontPreviewSize()}finally{this.inResize=null}}}measureElement(){if(!this.dummyElement)throw new Error("No font preview loaded");this.element.appendChild(this.dummyElement);const e={width:this.dummyElement.offsetWidth,height:this.dummyElement.offsetHeight};return this.element.removeChild(this.dummyElement),e}updateFontPreviewSize(){if(!this.fontPreviewElement||!this.isShowing())return;this.fontPreviewElement.style.removeProperty("visibility");const e=this.measureElement(),t=e.height,r=e.width,n=this.element.offsetWidth-50,i=this.element.offsetHeight-30;if(!(t&&r&&n&&i))return void this.fontPreviewElement.style.removeProperty("font-size");const s=n/r,o=i/t,a=Math.floor(G*Math.min(s,o))-2;this.fontPreviewElement.style.setProperty("font-size",a+"px",void 0)}}let J=0;const X=["ABCDEFGHIJKLM","NOPQRSTUVWXYZ","abcdefghijklm","nopqrstuvwxyz","1234567890"],G=50;var $=Object.freeze({__proto__:null,FontView:q}),Q={cssContent:".image-view{overflow:auto}.image-view > .image{padding:20px 20px 10px;text-align:center}.image-view img.resource-image-view{max-width:100%;max-height:1000px;background-image:var(--image-file-checker);box-shadow:0 5px 10px var(--box-shadow-outline-color);user-select:text;-webkit-user-drag:auto}"};const Y={image:"Image",dropImageFileHere:"Drop image file here",imageFromS:"Image from {PH1}",dD:"{PH1} × {PH2}",copyImageUrl:"Copy image URL",copyImageAsDataUri:"Copy image as data URI",openImageInNewTab:"Open image in new tab",saveImageAs:"Save image as...",download:"download"},K=t.i18n.registerUIStrings("ui/legacy/components/source_frame/ImageView.ts",Y),Z=t.i18n.getLocalizedString.bind(void 0,K);class ee extends r.View.SimpleView{url;parsedURL;mimeType;contentProvider;uiSourceCode;sizeLabel;dimensionsLabel;aspectRatioLabel;mimeTypeLabel;container;imagePreviewElement;cachedContent;constructor(e,t){super(Z(Y.image)),this.registerRequiredCSS(Q),this.element.tabIndex=-1,this.element.classList.add("image-view"),this.url=t.contentURL(),this.parsedURL=new n.ParsedURL.ParsedURL(this.url),this.mimeType=e,this.contentProvider=t,this.uiSourceCode=t instanceof h.UISourceCode.UISourceCode?t:null,this.uiSourceCode&&(this.uiSourceCode.addEventListener(h.UISourceCode.Events.WorkingCopyCommitted,this.workingCopyCommitted,this),new r.DropTarget.DropTarget(this.element,[r.DropTarget.Type.ImageFile,r.DropTarget.Type.URI],Z(Y.dropImageFileHere),this.handleDrop.bind(this))),this.sizeLabel=new r.Toolbar.ToolbarText,this.dimensionsLabel=new r.Toolbar.ToolbarText,this.aspectRatioLabel=new r.Toolbar.ToolbarText,this.mimeTypeLabel=new r.Toolbar.ToolbarText(e),this.container=this.element.createChild("div","image"),this.imagePreviewElement=this.container.createChild("img","resource-image-view"),this.imagePreviewElement.addEventListener("contextmenu",this.contextMenu.bind(this),!0)}async toolbarItems(){return await this.updateContentIfNeeded(),[this.sizeLabel,new r.Toolbar.ToolbarSeparator,this.dimensionsLabel,new r.Toolbar.ToolbarSeparator,this.aspectRatioLabel,new r.Toolbar.ToolbarSeparator,this.mimeTypeLabel]}wasShown(){this.updateContentIfNeeded()}disposeView(){this.uiSourceCode&&this.uiSourceCode.removeEventListener(h.UISourceCode.Events.WorkingCopyCommitted,this.workingCopyCommitted,this)}workingCopyCommitted(){this.updateContentIfNeeded()}async updateContentIfNeeded(){const t=await this.contentProvider.requestContent();if(this.cachedContent?.content===t.content)return;this.cachedContent=t;const r=e.ContentProvider.contentAsDataURL(t.content,this.mimeType,t.isEncoded)||this.url,n=new Promise((e=>{this.imagePreviewElement.onload=e}));this.imagePreviewElement.src=r,this.imagePreviewElement.alt=Z(Y.imageFromS,{PH1:this.url});const s=t.content&&!t.isEncoded?t.content.length:i.StringUtilities.base64ToSize(t.content);this.sizeLabel.setText(i.NumberUtilities.bytesToString(s)),await n,this.dimensionsLabel.setText(Z(Y.dD,{PH1:this.imagePreviewElement.naturalWidth,PH2:this.imagePreviewElement.naturalHeight})),this.aspectRatioLabel.setText(i.NumberUtilities.aspectRatio(this.imagePreviewElement.naturalWidth,this.imagePreviewElement.naturalHeight))}contextMenu(e){const t=new r.ContextMenu.ContextMenu(e),i=new n.ParsedURL.ParsedURL(this.imagePreviewElement.src);this.parsedURL.isDataURL()||t.clipboardSection().appendItem(Z(Y.copyImageUrl),this.copyImageURL.bind(this)),i.isDataURL()&&t.clipboardSection().appendItem(Z(Y.copyImageAsDataUri),this.copyImageAsDataURL.bind(this)),t.clipboardSection().appendItem(Z(Y.openImageInNewTab),this.openInNewTab.bind(this)),t.clipboardSection().appendItem(Z(Y.saveImageAs),(async()=>{await this.saveImage()})),t.show()}copyImageAsDataURL(){c.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(this.imagePreviewElement.src)}copyImageURL(){c.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(this.url)}async saveImage(){if(!this.cachedContent||!this.cachedContent.content)return;const t=e.ContentProvider.contentAsDataURL(this.cachedContent.content,this.mimeType,this.cachedContent.isEncoded,"",!1);if(!t)return;const r=document.createElement("a");r.href=t,r.download=this.parsedURL.isDataURL()?Z(Y.download):decodeURIComponent(this.parsedURL.displayName),r.click(),r.remove()}openInNewTab(){c.InspectorFrontendHost.InspectorFrontendHostInstance.openInNewTab(this.url)}async handleDrop(e){const t=e.items;if(!t.length||"file"!==t[0].kind)return;const r=t[0].getAsFile();if(!r)return;const n=!r.name.endsWith(".svg");(e=>{const t=new FileReader;t.onloadend=()=>{let e;try{e=t.result}catch(t){e=null,console.error("Can't read file: "+t)}"string"==typeof e&&this.uiSourceCode&&this.uiSourceCode.setContent(n?btoa(e):e,n)},n?t.readAsBinaryString(e):t.readAsText(e)})(r)}}var te=Object.freeze({__proto__:null,ImageView:ee}),re={cssContent:".json-view{padding:2px 6px;overflow:auto}"};const ne={find:"Find"},ie=t.i18n.registerUIStrings("ui/legacy/components/source_frame/JSONView.ts",ne),se=t.i18n.getLocalizedString.bind(void 0,ie);class oe extends r.Widget.VBox{initialized;parsedJSON;startCollapsed;searchableView;treeOutline;currentSearchFocusIndex;currentSearchTreeElements;searchRegex;constructor(e,t){super(),this.initialized=!1,this.registerRequiredCSS(re),this.parsedJSON=e,this.startCollapsed=Boolean(t),this.element.classList.add("json-view"),this.currentSearchFocusIndex=0,this.currentSearchTreeElements=[],this.searchRegex=null}static async createView(e){const t=await oe.parseJSON(e);if(!t||"object"!=typeof t.data)return null;const n=new oe(t),i=new r.SearchableView.SearchableView(n,null);return i.setPlaceholder(se(ne.find)),n.searchableView=i,n.show(i.element),i}static createViewSync(e){const t=new oe(new ae(e,"","")),n=new r.SearchableView.SearchableView(t,null);return n.setPlaceholder(se(ne.find)),t.searchableView=n,t.show(n.element),t.element.tabIndex=0,n}static parseJSON(e){let t=null;if(e&&(t=oe.extractJSON(e)),!t)return Promise.resolve(null);try{const e=JSON.parse(t.data);if(!e)return Promise.resolve(null);t.data=e}catch(e){t=null}return Promise.resolve(t)}static extractJSON(e){if(e.startsWith("<"))return null;let t=oe.findBrackets(e,"{","}");const r=oe.findBrackets(e,"[","]");if(t=r.length>t.length?r:t,-1===t.length||e.length-t.length>80)return null;const n=e.substring(0,t.start),i=e.substring(t.end+1);return e=e.substring(t.start,t.end+1),!i.trim().length||i.trim().startsWith(")")&&n.trim().endsWith("(")?new ae(e,n,i):null}static findBrackets(e,t,r){const n=e.indexOf(t),i=e.lastIndexOf(r);let s=i-n-1;return(-1===n||-1===i||i<n)&&(s=-1),{start:n,end:i,length:s}}wasShown(){this.initialize()}initialize(){if(this.initialized)return;this.initialized=!0;const e=d.RemoteObject.RemoteObject.fromLocalObject(this.parsedJSON.data),t=this.parsedJSON.prefix+e.description+this.parsedJSON.suffix;this.treeOutline=new u.ObjectPropertiesSection.ObjectPropertiesSection(e,t,void 0,!0),this.treeOutline.enableContextMenu(),this.treeOutline.setEditable(!1),this.startCollapsed||this.treeOutline.expand(),this.element.appendChild(this.treeOutline.element);const r=this.treeOutline.firstChild();r&&r.select(!0,!1)}jumpToMatch(e){if(!this.searchRegex)return;const t=this.currentSearchTreeElements[this.currentSearchFocusIndex];t&&t.setSearchRegex(this.searchRegex);const n=this.currentSearchTreeElements[e];n?(this.updateSearchIndex(e),n.setSearchRegex(this.searchRegex,r.UIUtils.highlightedCurrentSearchResultClassName),n.reveal()):this.updateSearchIndex(0)}updateSearchCount(e){this.searchableView&&this.searchableView.updateSearchMatchesCount(e)}updateSearchIndex(e){this.currentSearchFocusIndex=e,this.searchableView&&this.searchableView.updateCurrentMatchIndex(e)}onSearchCanceled(){let e;for(this.searchRegex=null,this.currentSearchTreeElements=[],e=this.treeOutline.rootElement();e;e=e.traverseNextTreeElement(!1))e instanceof u.ObjectPropertiesSection.ObjectPropertyTreeElement&&e.revertHighlightChanges();this.updateSearchCount(0),this.updateSearchIndex(0)}performSearch(e,t,r){let n=this.currentSearchFocusIndex;const s=this.currentSearchTreeElements[n];let o;for(this.onSearchCanceled(),this.searchRegex=e.toSearchRegex(!0).regex,o=this.treeOutline.rootElement();o;o=o.traverseNextTreeElement(!1)){if(!(o instanceof u.ObjectPropertiesSection.ObjectPropertyTreeElement))continue;const e=o.setSearchRegex(this.searchRegex);if(e&&this.currentSearchTreeElements.push(o),s===o){const t=this.currentSearchTreeElements.length-1;n=e||r?t:t+1}}this.updateSearchCount(this.currentSearchTreeElements.length),this.currentSearchTreeElements.length?(n=i.NumberUtilities.mod(n,this.currentSearchTreeElements.length),this.jumpToMatch(n)):this.updateSearchIndex(-1)}jumpToNextSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=i.NumberUtilities.mod(this.currentSearchFocusIndex+1,this.currentSearchTreeElements.length);this.jumpToMatch(e)}jumpToPreviousSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=i.NumberUtilities.mod(this.currentSearchFocusIndex-1,this.currentSearchTreeElements.length);this.jumpToMatch(e)}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}}class ae{data;prefix;suffix;constructor(e,t,r){this.data=e,this.prefix=t,this.suffix=r}}var le=Object.freeze({__proto__:null,JSONView:oe,ParsedJSON:ae}),ce={cssContent:".tree-outline ol{list-style:none;padding:0;margin:0;padding-inline-start:16px;--override-xml-view-tag:rgb(136 18 128);--override-xml-view-comment-or-instruction:rgb(35 110 37);--override-xml-view-attribute-name:rgb(153 69 0);--override-xml-view-attribute-value:rgb(26 26 166)}.-theme-with-dark-background .tree-outline ol,\n:host-context(.-theme-with-dark-background) .tree-outline ol{--override-xml-view-tag:rgb(237 119 229);--override-xml-view-comment-or-instruction:rgb(145 220 147);--override-xml-view-attribute-name:rgb(255 171 102);--override-xml-view-attribute-value:rgb(89 89 229)}ol.tree-outline{padding-inline-start:0}.tree-outline li{min-height:12px}.tree-outline li.shadow-xml-view-close-tag{margin-left:-16px}.shadow-xml-view-tag{color:var(--override-xml-view-tag)}.shadow-xml-view-comment{color:var(--override-xml-view-comment-or-instruction)}.shadow-xml-view-processing-instruction{color:var(--override-xml-view-comment-or-instruction)}.shadow-xml-view-attribute-name{color:var(--override-xml-view-attribute-name)}.shadow-xml-view-attribute-value{color:var(--override-xml-view-attribute-value)}.shadow-xml-view-text{color:var(--color-background-inverted);white-space:pre}.shadow-xml-view-cdata{color:var(--color-background-inverted)}"},he={cssContent:".shadow-xml-view{user-select:text;overflow:auto;padding:2px 4px}"};const de={find:"Find"},ue=t.i18n.registerUIStrings("ui/legacy/components/source_frame/XMLView.ts",de),me=t.i18n.getLocalizedString.bind(void 0,ue);class pe extends r.Widget.Widget{treeOutline;searchableView;currentSearchFocusIndex;currentSearchTreeElements;searchConfig;constructor(e){super(!0),this.registerRequiredCSS(he),this.contentElement.classList.add("shadow-xml-view","source-code"),this.treeOutline=new r.TreeOutline.TreeOutlineInShadow,this.treeOutline.registerRequiredCSS(ce),this.contentElement.appendChild(this.treeOutline.element),this.currentSearchFocusIndex=0,this.currentSearchTreeElements=[],ge.populate(this.treeOutline,e,this);const t=this.treeOutline.firstChild();t&&t.select(!0,!1)}static createSearchableView(e){const t=new pe(e),n=new r.SearchableView.SearchableView(t,null);return n.setPlaceholder(me(de.find)),t.searchableView=n,t.show(n.element),n}static parseXML(e,t){let r;try{switch(t){case"application/xhtml+xml":case"application/xml":case"image/svg+xml":case"text/html":case"text/xml":r=(new DOMParser).parseFromString(e,t)}}catch(e){return null}return!r||r.body?null:r}jumpToMatch(e,t){if(!this.searchConfig)return;const{regex:n}=this.searchConfig.toSearchRegex(!0),i=this.currentSearchTreeElements[this.currentSearchFocusIndex];i&&i.setSearchRegex(n);const s=this.currentSearchTreeElements[e];s?(this.updateSearchIndex(e),t&&s.reveal(!0),s.setSearchRegex(n,r.UIUtils.highlightedCurrentSearchResultClassName)):this.updateSearchIndex(0)}updateSearchCount(e){this.searchableView&&this.searchableView.updateSearchMatchesCount(e)}updateSearchIndex(e){this.currentSearchFocusIndex=e,this.searchableView&&this.searchableView.updateCurrentMatchIndex(e)}innerPerformSearch(e,t){if(!this.searchConfig)return;let r=this.currentSearchFocusIndex;const n=this.currentSearchTreeElements[r];this.innerSearchCanceled(),this.currentSearchTreeElements=[];const{regex:s}=this.searchConfig.toSearchRegex(!0);for(let e=this.treeOutline.rootElement();e;e=e.traverseNextTreeElement(!1)){if(!(e instanceof ge))continue;const i=e.setSearchRegex(s);if(i&&this.currentSearchTreeElements.push(e),n===e){const e=this.currentSearchTreeElements.length-1;r=i||t?e:e+1}}this.updateSearchCount(this.currentSearchTreeElements.length),this.currentSearchTreeElements.length?(r=i.NumberUtilities.mod(r,this.currentSearchTreeElements.length),this.jumpToMatch(r,e)):this.updateSearchIndex(0)}innerSearchCanceled(){for(let e=this.treeOutline.rootElement();e;e=e.traverseNextTreeElement(!1))e instanceof ge&&e.revertHighlightChanges();this.updateSearchCount(0),this.updateSearchIndex(0)}onSearchCanceled(){this.searchConfig=null,this.currentSearchTreeElements=[],this.innerSearchCanceled()}performSearch(e,t,r){this.searchConfig=e,this.innerPerformSearch(t,r)}jumpToNextSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=i.NumberUtilities.mod(this.currentSearchFocusIndex+1,this.currentSearchTreeElements.length);this.jumpToMatch(e,!0)}jumpToPreviousSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=i.NumberUtilities.mod(this.currentSearchFocusIndex-1,this.currentSearchTreeElements.length);this.jumpToMatch(e,!0)}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}}class ge extends r.TreeOutline.TreeElement{node;closeTag;highlightChanges;xmlView;constructor(e,t,r){super("",!t&&"childElementCount"in e&&Boolean(e.childElementCount)),this.node=e,this.closeTag=t,this.selectable=!0,this.highlightChanges=[],this.xmlView=r,this.updateTitle()}static populate(e,t,r){if(!(t instanceof Node))return;let n=t.firstChild;for(;n;){const t=n;n=n.nextSibling;const i=t.nodeType;3===i&&t.nodeValue&&t.nodeValue.match(/\s+/)||(1!==i&&3!==i&&4!==i&&7!==i&&8!==i||e.appendChild(new ge(t,!1,r)))}}setSearchRegex(t,n){if(this.revertHighlightChanges(),!t)return!1;if(this.closeTag&&this.parent&&!this.parent.expanded)return!1;t.lastIndex=0;let i=r.UIUtils.highlightedSearchResultClassName;if(n&&(i+=" "+n),!this.listItemElement.textContent)return!1;const s=this.listItemElement.textContent.replace(/\xA0/g," ");let o=t.exec(s);const a=[];for(;o;)a.push(new e.TextRange.SourceRange(o.index,o[0].length)),o=t.exec(s);return a.length&&r.UIUtils.highlightRangesWithStyleClass(this.listItemElement,a,i,this.highlightChanges),Boolean(this.highlightChanges.length)}revertHighlightChanges(){r.UIUtils.revertDomChanges(this.highlightChanges),this.highlightChanges=[]}updateTitle(){const e=this.node;if("nodeType"in e)switch(e.nodeType){case 1:if(e instanceof Element){const t=e.tagName;if(this.closeTag)return void this.setTitle(["</"+t+">","shadow-xml-view-tag"]);const r=["<"+t,"shadow-xml-view-tag"],n=e.attributes;for(let e=0;e<n.length;++e){const t=n.item(e);if(!t)return;r.push(" ","shadow-xml-view-tag",t.name,"shadow-xml-view-attribute-name",'="',"shadow-xml-view-tag",t.value,"shadow-xml-view-attribute-value",'"',"shadow-xml-view-tag")}return this.expanded||(e.childElementCount?r.push(">","shadow-xml-view-tag","…","shadow-xml-view-comment","</"+t,"shadow-xml-view-tag"):e.textContent?r.push(">","shadow-xml-view-tag",e.textContent,"shadow-xml-view-text","</"+t,"shadow-xml-view-tag"):r.push(" /","shadow-xml-view-tag")),r.push(">","shadow-xml-view-tag"),void this.setTitle(r)}return;case 3:return void(e.nodeValue&&this.setTitle([e.nodeValue,"shadow-xml-view-text"]));case 4:return void(e.nodeValue&&this.setTitle(["<![CDATA[","shadow-xml-view-cdata",e.nodeValue,"shadow-xml-view-text","]]>","shadow-xml-view-cdata"]));case 7:return void(e.nodeValue&&this.setTitle(["<?"+e.nodeName+" "+e.nodeValue+"?>","shadow-xml-view-processing-instruction"]));case 8:return void this.setTitle(["\x3c!--"+e.nodeValue+"--\x3e","shadow-xml-view-comment"])}}setTitle(e){const t=document.createDocumentFragment();for(let r=0;r<e.length;r+=2)t.createChild("span",e[r+1]).textContent=e[r];this.title=t,this.xmlView.innerPerformSearch(!1,!1)}onattach(){this.listItemElement.classList.toggle("shadow-xml-view-close-tag",this.closeTag)}onexpand(){this.updateTitle()}oncollapse(){this.updateTitle()}async onpopulate(){ge.populate(this,this.node,this.xmlView),this.appendChild(new ge(this.node,!0,this.xmlView))}}var we=Object.freeze({__proto__:null,XMLView:pe,XMLViewNode:ge});const fe={nothingToPreview:"Nothing to preview"},xe=t.i18n.registerUIStrings("ui/legacy/components/source_frame/PreviewFactory.ts",fe),Se=t.i18n.getLocalizedString.bind(void 0,xe);var be=Object.freeze({__proto__:null,PreviewFactory:class{static async createPreview(e,t){let i=n.ResourceType.ResourceType.fromMimeType(t);switch(i===n.ResourceType.resourceTypes.Other&&(i=e.contentType()),i){case n.ResourceType.resourceTypes.Image:return new ee(t,e);case n.ResourceType.resourceTypes.Font:return new q(t,e)}const s=await e.requestContent();if(null===s.content)return new r.EmptyWidget.EmptyWidget(s.error);if(!s.content)return new r.EmptyWidget.EmptyWidget(Se(fe.nothingToPreview));let o=s.content;s.isEncoded&&(o=window.atob(o));const a=pe.parseXML(o,t);if(a)return pe.createSearchableView(a);const l=await oe.createView(o);if(l)return l;if(i.isTextType()){const r=t.replace(/;.*/,"")||e.contentType().canonicalMimeType();return D.createSearchableView(e,r,!0)}return null}}});export{A as BinaryResourceViewFactory,$ as FontView,te as ImageView,le as JSONView,be as PreviewFactory,H as ResourceSourceFrame,F as SourceFrame,we as XMLView};
